<template>
  <div class="content">
    <div class="basicInfo">
      <div style="flex: 1.5;">
        <span>
          赛事名称：
          <b>{{pageData.name}}</b>
        </span>
        <span>
          裁判长：
          <b>{{pageData.referee}}</b>
        </span>
      </div>
    </div>

    <div style="margin-top:50px;">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="所报名组别:" prop="name">
          <p>{{pageData.com_project}}</p>
        </el-form-item>

        <el-row>
          <el-col :span="10">
            <el-form-item label="添加运动员:" prop="region">
              <el-form-item label="系统内运动员:">
								 <el-select v-model="referee_id"  style="width: 100%;" filterable remote reserve-keyword size="medium" placeholder="请输入姓名/电话号码/身份证号码"
								   :remote-method="seachUser" :loading="searchingRef">
								   <el-option v-for="(item,index) in search_UserList" :key="item.user_id" :label="item.searchName" :value="item.user_id"  @click.native="selectUser(index)"></el-option>
								 </el-select>
              </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="teamShow">
          <el-col :span='10'>
            <el-form-item>
              <el-form-item label="团体名称">
                <el-input v-model="formLabelAlign.team_name"></el-input>
              </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item>
            <el-form-item label="姓名:">
              <el-input maxlength=10 v-model="formLabelAlign.name"></el-input>
            </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item>
            <el-form-item label="年龄:">
              <el-input maxlength=2 type="number" v-model="formLabelAlign.age"></el-input>
            </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item>
            <el-form-item label="性别:">
              <el-select v-model="formLabelAlign.sex" placeholder="请选择性别" style="width: 100%;">
                  <el-option
                    v-for="item in gender"
                    :key="item.value"
                    :value="item.value">
                  </el-option>
                </el-select>
            </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item>
            <el-form-item label="手机号:">
              <el-input maxlength=11  type="tel" v-model="formLabelAlign.phone"></el-input>
            </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row >
          <el-col :span="10">
            <el-form-item>
            <el-form-item label="身份证号码:">
              <el-input maxlength=18 v-model="formLabelAlign.cardID"></el-input>
            </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="ref1">
          <el-col :span="10">
            <el-form-item >
            <el-form-item prop='refs1' :label="pageData.require[0]" >
              <el-input v-model="formLabelAlign.orther0"  placeholder="请输入一级单位"></el-input>
            </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="ref2">
          <el-col :span="10">
            <el-form-item>
            <el-form-item prop='refs2' :label="pageData.require[1]">
              <el-input v-model="formLabelAlign.orther1"  placeholder='请输入二级单位'></el-input>
            </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="ref3">
          <el-col :span="10">
            <el-form-item>
            <el-form-item prop='refs3' :label="pageData.require[2]">
              <el-input style="min-width:300px;" v-model="formLabelAlign.orther2" placeholder='请输入三级单位'></el-input>
            </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="3" :offset="1">
              <el-button style="position: absolute;right: 45%;bottom: 20px;" @click="confirm">确认</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="table">
      <el-table :data="tableData" stripe style="width: 100%;" border>
        <el-table-column prop="user_id" label="Id" width="100"></el-table-column>
        <el-table-column v-if="teamShow" prop="team_name" label="团体名称" width="100"></el-table-column>
        <el-table-column prop="name" label="姓名" width="100"></el-table-column>
        <el-table-column prop="age" label="年龄"></el-table-column>
        <el-table-column prop="sex" label="性别"></el-table-column>
        <el-table-column prop="group" label="项目-组别" width="200"></el-table-column>
        <!-- <el-table-column  prop="team_name" label="团体名称"></el-table-column> -->
        <el-table-column prop="id_card" label="身份证号" width="200"></el-table-column>
        <el-table-column prop="phone" label="手机号"  width="150"></el-table-column>
        <el-table-column prop="customize" label="单位"></el-table-column>
        <el-table-column prop="price" label="价格"></el-table-column>
        <el-table-column prop="option" label="操作" width="100">
          <template slot-scope="scope">
            <p :style="{color:'#409eff',cursor: 'pointer'}"  @click="remove(scope.row)">{{scope.row.option}}</p>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="total" v-if="!teamShow">价格总计：{{totalPrice}}</div>

    <div style="margin-top:100px">
      <el-button type="primary" @click="isSigned">提交</el-button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      twice:false,
      teamShow:false,
      mix:false,
      options:{},//团体列表
      teamList:[],
      pageData: {},
      tableData: [],
      dataList:[],
      keywords: "",
      rowId:0,
      ruleForm: {},
      ref1:false,
      ref2:false,
      ref3:false,
			indexData:0,
			arrData:[],//索引下标
			userPhoneOrNameData:'',
			referee_id:'',
			userIdCard:'',
      rules: {
        name: [{ required: true, message: "", trigger: "blur" }],
        region: [{ required: true, message: "" }],
      },
			search_UserList:[],
      state:'',
			searchingRef: false,
      formLabelAlign: {
        team_name:"",
        name: "",
        age:"",
        sex: "",
        phone: "",
        cardID: "",
        orther0:"",
        orther1:"",
        orther2:"",
        orther: ""
      },
			gender:[
				{
					value:'男'
				},
				{
					value:'女'	
				}
			],
      totalPrice:0
    };
  },
  created() {
    this.getSignInfor();
  },
  watch:{
    keywords: function (str) {
        if (typeof str ==='string'){
            if (str.trim().length!==0){
                this.debounce(this.serach,1000);
            }else {}
        }
    }
},
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 跳转到报名列表页
    goSignList(){
      let showTeam =  this.teamShow
      let com_id  = this.$route.query.com_id;
      this.$router.push('/Index/signList?com_id='+com_id+'showTeam='+showTeam)
    },
    // 计算总价格
    sumPrice(){
      let priceArr = []
      let stary = []
      let totalPrice = 0
      if(this.twice){
        for (const index in this.tableData) {
          priceArr.push(parseFloat(this.tableData[0].price))
        }
        totalPrice = priceArr.reduce((a,b)=>{
          return a+b
        },0)
        this.totalPrice = totalPrice/2
        return
      }
      for (const index in this.tableData) {
        priceArr.push(parseFloat(this.tableData[0].price))
      }
      this.totalPrice = priceArr.reduce((a,b)=>{
        return a+b
      },0)
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 移除运动员
    remove(row){
      // console.log(row)
      let arr1 = []
      let arr2 = []
      arr1.push({user_id:row.user_id})
      for(var index in this.tableData){
        arr2.push({user_id1:this.tableData[index].user_id})
        if(arr1[0].user_id==arr2[index].user_id1){
          this.tableData.splice(index,1)
        }else{
          console.log(arr1[0].user_id,arr2[index].user_id1)
        }
      }
			this.$message({
				message:'移除成功',
				type:'success'
			})
      this.sumPrice()
    },
    // 表单验证和数据暂存
    async confirm() {
      let formLabelAlign = this.formLabelAlign;
      let tableData = this.tableData;
      let item = this.pageData;
      if(this.teamShow){
        if(!formLabelAlign.team_name){
          this.$message({
            message: '请填写团体名称',
            type: 'warning'
          });
          return
        }
      }
      if(!formLabelAlign.name){
         this.$message({
          message: '请填写姓名',
          type: 'warning'
        });
        return
      }else{
        if(formLabelAlign.name.length>20||formLabelAlign.name.length<2){
          this.$message({
            message: '姓名必须在2~20个字符之间',
            type: 'warning'
          });
          return
        }
      }
      if(!formLabelAlign.age){
         this.$message({
          message: '请填写年龄',
          type: 'warning'
        });
        return
      }else{
        if(formLabelAlign.age<4){
          this.$message({
            message: '年龄太小了',
            type: 'warning'
          });
          return
        }else if(formLabelAlign.age>80){
          this.$message({
            message: '年龄太大了',
            type: 'warning'
          });
          return
        }
      }
      if(!formLabelAlign.sex){
         this.$message({
          message: '请填写性别',
          type: 'warning'
        });
        return
      }else{
        // 性别为女
        if(formLabelAlign.sex!=='男'){
          let arr = []
          arr.push({
            sex:this.pageData.com_project
          })
          // 项目为男生项目时
          if(arr[0].sex.indexOf('女')==-1&&!this.mix){
            this.$message({
              message: '该赛事组别女生不能报名',
              type: 'warning'
            });
            return
          }
        }else{
          // 性别为男
          if(formLabelAlign.sex!=='女'){
            let arr = []
            arr.push({
              sex:this.pageData.com_project
            })
            // 组别只能女生报名时
            if(arr[0].sex.indexOf('男')==-1&&!this.mix){
              this.$message({
                message: '该赛事组别男生不能报名',
                type: 'warning'
              });
              return
            }
          }
        }
      }
      if(!formLabelAlign.phone){
         this.$message({
          message: '请填写电话号码',
          type: 'warning'
        });
        return
      }else{
        var pattern = /^1[3-9]\d{9}$/
        let check = pattern.test(formLabelAlign.phone)
        if(!check){
          this.$message({
            message: '请输入正确的11位手机号码',
            type: 'warning'
          });
          return
        }
      }
      if(!formLabelAlign.cardID){
         this.$message({
          message: '请填写身份证号码',
          type: 'warning'
        });
        return
      }else{
        var pattern = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
        let check = pattern.test(formLabelAlign.cardID)
        if(!check){
          this.$message({
            message: '请输入正确的18位身份证号码尾数为X的请输入英文X大小写均可',
            type: 'warning'
          });
          return
        }
      }
      if(this.ref1){
        if(formLabelAlign.orther0==undefined){
          this.$message({
            message: '请填写一级单位',
            type: 'warning'
          });
          return
        }else{
          this.formLabelAlign.orther=this.formLabelAlign.orther0
        }
      }
      if(this.ref2){
        if(formLabelAlign.orther1==undefined){
          this.$message({
            message: '请填写二级单位',
            type: 'warning'
          });
          return
        }else{
          this.formLabelAlign.orther=this.formLabelAlign.orther0+','+this.formLabelAlign.orther1
        }
      }
      if(this.ref3){
        if(formLabelAlign.orther2==undefined){
          this.$message({
            message: '请填写三级单位',
            type: 'warning'
          });
          return
        }else{
          this.formLabelAlign.orther=this.formLabelAlign.orther0+','+this.formLabelAlign.orther1+','+this.formLabelAlign.orther2
        }
      }
      try{
        let res = await this.$axios.post("/TeamSign/idcard",
          {
            name:this.formLabelAlign.name,
            idCard:this.formLabelAlign.cardID
          },
          {
            headers: {
              token: window.sessionStorage.getItem("token")
            }
          })
          console.log(res)
          if(res.data.code==400){
             this.$message({
               message: res.data.message,
               type: 'danger'
             });
            return
          }else if(res.data.code==2000){
            this.$message({
              message: res.data.data.msg,
              type: 'success'
            });
          }else{
            this.$message({
              message: res.data.msg,
              type: 'danger'
            });
            return
          }
      }catch(e){
        console.log(e)
        //TODO handle the exception
      }
      tableData.push({
        name: this.formLabelAlign.name,
        project_id: this.$route.query.group_id,
        group:this.pageData.com_project,
        age:this.formLabelAlign.age,
        id_card: this.formLabelAlign.cardID,
        sex: this.formLabelAlign.sex,
        phone: this.formLabelAlign.phone,
        customize: this.formLabelAlign.orther,
        price: item.price,
        team_name:this.teamShow?this.formLabelAlign.team_name:'',
        option: "移除",
        user_id:this.formLabelAlign.user_id,
        com_id:this.$route.query.com_id,
        sign_id:sessionStorage.getItem('user_id')
      });

      this.tableData = tableData;
      if(this.teamShow){
        this.formLabelAlign = {
          team_name:this.formLabelAlign.team_name,
          name: "",
          age:"",
          sex: "",
          phone: "",
          cardID: "",
          orther0:formLabelAlign.orther0,
          orther1:formLabelAlign.orther1,
          orther2:formLabelAlign.orther2,
        };
        return
      }
      this.formLabelAlign = {
        name: "",
        age:"",
        sex: "",
        phone: "",
        cardID: "",
        orther0:"",
        orther1:"",
        orther2:"",
        orther: "",
        user_id:""
      };
      this.sumPrice()
    },
    createFilter(queryString) {
      return (state) => {
        return (state.searchName.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
			console.log(item)
      let  formLabelAlign = {
          team_name:'',
          name: item.name,
          sex: item.sex == 0 ? "男" : "女",
          phone: item.phone,
          cardID: item.id_card,
          user_id:item.user_id
        };
      this.formLabelAlign = formLabelAlign;
    },
    //防抖函数
    debounce:function(fn,wait){
        if (this.fun!==null){
            clearTimeout(this.fun)
        }
        this.fun = setTimeout(fn,wait)
    },
		//搜索运动员
		seachUser(query){
			this.searchingRef = true;
			this.$axios
			  .get("/TeamSign/search_user", {
			    params: {
			      search: query
			    },
			    headers: {
			      token: sessionStorage.getItem("token")
			    }
			  })
			  .then(result => {
					this.$message({
						message:result.data.message,
						type:'success'
					})
			    let data = result.data.data;
			    this.search_UserList = data;
					console.log(this.search_UserList)
					var dataList = data;
					this.handleSelect(dataList)
					for(var index in dataList){
					  dataList[index].searchName = dataList[index].name+'-'+dataList[index].id_card
					}
			    this.searchingRef = false;
			  });
		},
		selectUser(index) {
			this.handleSelect(this.search_UserList[index])
		  this.indexData = index;
		  this.arrData = this.search_UserList.slice(0);
		  this.userPhoneOrNameData =
		    this.search_UserList[index].name +
		    "/" +
		    this.search_UserList[index].phone;
		  this.referee_id = this.search_UserList[index].id;
			this.userIdCard = this.search_UserList[index].id_card
			console.log(this.search_UserList)
		},
    //搜索运动员----此方法已废弃
    async serach(queryString, cb) {
			this.searchingRef = true;
      try {
        let result = await this.$axios.post(
          "/TeamSign/search_user",
          {
            search: this.state
          },
          {
            headers: {
              token: window.sessionStorage.getItem("token")
            }
          }
        );
        if(result.data.data==''){
           this.$message({
              message: '查询不到该运动员',
              type: 'error'
            });
            return
        }
				this.searchingRef = false;
        this.dataList = result.data.data
        var dataList = this.dataList;
        for(var index in dataList){
          dataList[index].searchName = dataList[index].name+'-'+dataList[index].id_card
        }
        let results = queryString ? dataList.filter(this.createFilter(queryString)) : dataList;
        // 调用 callback 返回建议列表的数据
       clearTimeout(this.timeout);
       this.timeout = setTimeout(() => {
         cb(results);
       }, 1000 * Math.random());

      } catch (err) {
				this.$message({
				   message: err,
				   type: 'error'
				 });
        throw new Error(err);
      }
    },
    async isSigned(){
      // console.log(this.tableData)
      let tableInfo = this.tableData
      try {
        let res = await this.$axios.post(
          "/TeamSign/order_add",
          {
            tableInfo
          },
          {
            headers: {
              token: window.sessionStorage.getItem("token")
            }
          }
        );
        if(res.data.code==2000){
          this.$message({
            message: res.data.msg,
            type: 'success',
          });
          this.goSignList()
          return
        }
        if(res.data.code==400){
          let datas = []
          for (var index in res.data.data){
            datas.push({
              name:res.data.data[index]
            })
          }
          let arr = []
          datas.forEach((item)=>{
            arr.push(name=datas[index].name)
          })
          this.$message({
            message:res.data.message+':'+arr,
            type:'error'
          })
          return
        }
        this.$message(res.data.msg)
      } catch (err) {
				this.$message({
				  message: err,
				  type: 'error',
				});
        console.log(err)
      }
    },

    //获取报名信息
    async getSignInfor() {
      let { com_id, group_id } = this.$route.query;
      try {
        let result = await this.$axios.post(
          "/TeamSign/sign_info",
          {
            com_id,
            group_id
          },
          {
            headers: {
              token: window.sessionStorage.getItem("token")
            }
          }
        );
        if(result.data.status=='fail'){
          this.$message(result.data.message)
          return
        }
				this.$message({
				  message: result.data.message,
				  type: 'success',
				});
        this.options.teamName=result.data.data.com_project
        let teamarr = []
        teamarr.push(result.data.data.com_project)
        if(teamarr[0].indexOf("团")==-1){
          this.teamShow = false
        }else{
          this.teamShow = true
        }
        if(teamarr[0].indexOf("双")==-1){
          this.twice = false
        }else{
          this.twice = true
        }
        if(teamarr[0].indexOf("混")==-1){
          this.mix = false
        }else{
          this.mix = true
        }
        this.pageData = result.data.data;
        if(this.pageData.require.length==1){
            this.ref1 = true,
            this.ref2 = false,
            this.ref3 = false
        }
        if(this.pageData.require.length==2){
            this.ref1 = true,
            this.ref2 = true,
            this.ref3 = false
        }
        if(this.pageData.require.length==3){
            this.ref1 = true,
            this.ref2 = true,
            this.ref3 = true
        }

      } catch (err) {
        throw new Error(err);
      }
    }
  }
};
</script>

<style lang="less" scoped>
.content {
  width: 90%;
  height: 100%;
  padding-left: 46px;
  padding-top: 36px;
  box-sizing: border-box;
  .el-scrollbar__wrap {
    overflow-x: hidden;
  }
  .table {
    margin-top: 50px;
  }
}
.el-input{
  min-width: 300px!important;
}
.basicInfo {
  background: linear-gradient(
    90deg,
    rgba(66, 185, 131, 0.2),
    rgba(66, 185, 131, 0.4)
  );
  border-radius: 2px;
  line-height: 30px;
  height: 30px;
  padding: 15px;
  overflow: hidden;
  display: flex;
  justify-content: space-around;
  align-items: center;

  span {
    margin-right: 20px;
  }

  .btnGroup {
    /*height: 60px;*/
    /*float: right;*/
    margin-right: 20px;
}

  .date {
    width: 25%;
    padding: 10px 15px;
  }
}

.total {
  font-weight: bold;
  margin-top: 30px;
}
</style>
